package create.he.common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * sql 执行 
 * 需要重新封装executeQuery 、executeUpdate  和execute    
 * @author heh
 *
 */
public class Execute {
	
	/**
	 * 获取到一个列表集合
	 * @param sql
	 * @param conn
	 * @return
	 * @throws SQLException
	 */
	public  List<Map<String ,Object>> findList(String sql,Connection conn) throws SQLException {
		// 执行查询
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		// 转换为list
		List<Map<String ,Object>> convertList =this.convertList(rs);
		// 完成后关闭连接
		rs.close();
		stmt.close();
		return convertList;
	}
	
	/***
	 * 获取一个结果
	 * @param sql
	 * @param conn
	 * @return
	 * @throws SQLException
	 */
	public  Map<String ,Object> getMap(String sql,Connection conn) throws SQLException {
		// 执行查询
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		// 转换为map
		Map<String ,Object> convertMap =this.convertMap(rs);
		// 完成后关闭连接
		rs.close();
		stmt.close();
		return convertMap;
	}
	
	
	
	
	
	/**
	 * 将结果转换为list
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	private  List<Map<String ,Object>> convertList(ResultSet rs) throws SQLException {
		List<Map<String ,Object>> list = new ArrayList();
		java.sql.ResultSetMetaData metaData = rs.getMetaData();// 获取键名
		int columnCount = metaData.getColumnCount();// 获取列的数量
		while (rs.next()) {
			Map<String ,Object> rowData = new HashMap<String ,Object>();// 声明Map
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(metaData.getColumnName(i), rs.getObject(i));// 获取键名及值
			}
			list.add(rowData);
		}
		return list;
	}
	
	/**
	 * 将结果转换为map
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	private Map<String ,Object> convertMap(ResultSet rs) throws SQLException {
		java.sql.ResultSetMetaData metaData = rs.getMetaData();// 获取键名
		int columnCount = metaData.getColumnCount();// 获取列的数量
		Map<String ,Object> rowData = new HashMap<String ,Object>();// 声明Map
		rs.last(); 
		int rowCount = rs.getRow(); //获得ResultSet的总行数
		if (rowCount <= 1) {
			rs.beforeFirst();
			while (rs.next()) {
				for (int i = 1; i <= columnCount; i++) {
					rowData.put(metaData.getColumnName(i), rs.getObject(i));// 获取键名及值
				}
			}
 		} else {
			throw new RuntimeException("期望的返回结果为1个，但是实际返回结果为 " + columnCount + " 个。");
		}
		 
		return rowData;
	}
}
